package ws.jdbc.concurrent.driver.sqlserver.tds

import ws.utils.io.LittleEndianDataInputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
class CommonOfflineTest extends GroovyTestCase {
	static String host = "localhost"
	static int port = 5454
  static ServerSocket serverSocket

  static {
    serverSocket = new ServerSocket(port)
  }

  void setUp() {
    println "-----------------------------------------------------------------"
  }
  
  /* ----------------------------- TEST UTILITIES --------------------------- */
  static void sendData(Byte[] data) {
    Thread.start {
      def ios = serverSocket.accept()
      def os = new DataOutputStream(new BufferedOutputStream(ios.getOutputStream()))
      os.write(data)
      os.flush()
    }
  }

  static ByteBuffer receiveData(int size) {
    def sock = new Socket(host, port)
    def message = new TDSMessage()
    def array = new byte[size]
    
    def is = new DataInputStream(new BufferedInputStream(sock.getInputStream()))
    is.read(array)

    return ByteBuffer.allocate(size).
        order(ByteOrder.LITTLE_ENDIAN).
        put(array).
        position(0)
  }

   static ByteBuffer receiveDataWithSize(int size) {
    def sock = new Socket(host, port)
    def message = new TDSMessage()
    def array = new byte[size]

    def is = new DataInputStream(new BufferedInputStream(sock.getInputStream()))
    is.read(array)

    return ByteBuffer.allocate(4 + size).
        order(ByteOrder.LITTLE_ENDIAN).
        putInt(size).
        put(array).
        position(0)
  }
}

